<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Constants\ErrorCode;
use App\Model\data\CurrentShopData;
use App\Service\FlyShopService;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\HttpServer\Contract\RequestInterface;
use App\Common\Http\Response;

class ShopMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * 商城类
     * @var FlyShopService
     */
    private $flyShopService;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var Response
     */
    protected $response;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->flyShopService = $container->get(FlyShopService::class);
        $this->response = $container->get(Response::class);
        $this->request = $container->get(RequestInterface::class);

    }

    /**
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
//        return $handler->handle($request);
        // todo 需要前端区分当前登录店铺类型：电商、美食
        $shopModel = $this->flyShopService->getAdminShop(intval($this->request->getHeaderLine('admin_id')));
        if ($shopModel != null) {
            //商家是否正常
            if (in_array($shopModel->shop_state, [0, 2, 3]) || $shopModel->shop_type == 0) {
                return $this->response->error(ErrorCode::UNAUTHORIZED, "商家权限已被限制!");
            }
            //设置上下文
            return $handler->handle(CurrentShopData::setData($shopModel));
        }
        return $this->response->error(ErrorCode::UNAUTHORIZED, "无商家权限!");
    }
}